package com.bbznb.config;

import com.bbznb.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.InvocationHandler;
import java.util.concurrent.TimeUnit;

import static com.bbznb.common.UserS.USER_LOGIN;

@Component
public class MyInter implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
            return true;
        }
        String authorization = httpServletRequest.getHeader("Authorization");
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            throw new RuntimeException("token is null");
        }

        String token = authorization.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        if(claims==null){
            throw new  RuntimeException("token is null");
        }
        String username = claims.getSubject();
        String username1 = redisTemplate.opsForValue().get(USER_LOGIN);
        if(username1!=null&&username1.equals(username)){

        }
        else{
            throw new  RuntimeException("token is expired");
        }
        redisTemplate.expire(USER_LOGIN,30, TimeUnit.MINUTES);
        return true;
    }
}
